package com.walker.jdkapi.masterworker;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

public class Master {
	
	/**
	 * 请求接收队列
	 */
	private ConcurrentLinkedQueue<Product> concurrentLinkedDeque = new ConcurrentLinkedQueue<>();

	/**
	 * workers
	 */
	private HashMap<String, Thread> workers = new HashMap<>();
	
	/**
	 * 存放返回结果
	 */
	private ConcurrentHashMap<String, Object> resultMap = new ConcurrentHashMap<>();

	public Master(Worker worker, int workCount) {
		worker.setConcurrentLinkedDeque(concurrentLinkedDeque);
		worker.setResultMap(resultMap);
		for(int i=1;i<=workCount;i++) {
			workers.put("Worker 节点" + Integer.toString(i), new Thread(worker));
		}
	}
	
	/**
	 * 提交任务
	 */
	public void commit(Product product) {
		this.concurrentLinkedDeque.offer(product);
	}
	
	/**
	 * 执行任务
	 */
	public void execute() {
		for(Map.Entry<String, Thread> entry : workers.entrySet()) {
			entry.getValue().start();
		}
	}
	
	/**
	 * 获取结果
	 */
	public int getReulte() {
		int sum = 0;
		for(Map.Entry<String, Object> entry : resultMap.entrySet()) {
			sum = sum + (Integer)entry.getValue();
		}
		return sum;
	}
	
	/**
	 * 判断是否结束
	 * @return
	 */
	public boolean isComplete() {
		for(Map.Entry<String, Thread> entry : workers.entrySet()) {
			if(entry.getValue().getState() != Thread.State.TERMINATED) {
				return false;
			}
		}
		return true;
	}
}
